package com.xd.core.api.util;

import com.xd.core.api.http.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpUtil{

    //http请求
    public static String RequestForm(String Url,Map<String,String> Parms){
        if(Parms.isEmpty()){
            return  "参数不能为空！";
        }
        String PostParms = "";
        for (String key : Parms.keySet()) {
            if(!key.isEmpty()){
                PostParms += key + "="+Parms.get(key)+"&";
            }

        }
        PostParms = PostParms.substring(0,PostParms.length()-1);
        System.out.println("【请求参数】："+ PostParms);
        HttpSendModel httpSendModel = new HttpSendModel(Url + "?" + PostParms);
        httpSendModel.setMethod(HttpMethod.POST);



        SimpleHttpResponse response = null;
        try {
            response = doRequest(httpSendModel, "utf-8");
        } catch (Exception e) {
            return e.getMessage();
        }
        return response.getEntityString();

    }

    // json 报文请求
    public static String httpPostWithJSON(String url, String json) {

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();

        StringEntity entity = new StringEntity(json,"utf-8");//解决中文乱码问题
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        System.out.println("http 请求参数:"+json);
        HttpResponse resp;
        try {
            resp = client.execute(httpPost);
            if(resp.getStatusLine().getStatusCode() == 200) {
                HttpEntity he = resp.getEntity();
                String respContent = EntityUtils.toString(he,"UTF-8");
                return respContent;
            }
            else{
                return ("http请求异常:"+resp.getStatusLine().getStatusCode());
            }
        }catch (Exception e){
            return "http 请求出错:"+e;
        }
    }

    //上传文件请求
    public static String doUploadFile(Map<String, File> files, String url, Map<String, String> params) {
        if (StringUtils.isBlank(url) || null == files) {
            return null;
        }
        CloseableHttpClient httpClient =  HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));//设置请求的编码格式
            multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式
            if (files != null && files.size() > 0) {
                Set<Map.Entry<String, File>> entries = files.entrySet();
                for (Map.Entry<String, File> entry : entries) {
                    multipartEntityBuilder.addPart(entry.getKey(), new FileBody(entry.getValue()));
                }
            }
            ContentType contentType = ContentType.create("text/plain", "UTF-8");
            //如果有额外的请求参数
            if (params != null && !params.isEmpty()) {
                for (String key : params.keySet()) {
                    multipartEntityBuilder.addPart(key, new StringBody(params.get(key), contentType));
                }
            }
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(multipartEntityBuilder.build());
//	            httpPost.addHeader("Content-Type", "multipart/form-data; boundary=----------ThIs_Is_tHe_bouNdaRY_$");
            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            return EntityUtils.toString(response.getEntity(),"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }




    public static SimpleHttpResponse doRequest(HttpSendModel httpSendModel,
                                               String getCharSet) throws Exception {

        // 创建默认的httpClient客户端端
        SimpleHttpClient simpleHttpclient = new SimpleHttpClient();

        try {
            return doRequest(simpleHttpclient, httpSendModel, getCharSet);
        } finally {
            simpleHttpclient.getHttpclient().getConnectionManager().shutdown();
        }

    }

    /**
     * @param httpSendModel
     * @param getCharSet
     * @return
     * @throws Exception
     */
    public static SimpleHttpResponse doRequest(
            SimpleHttpClient simpleHttpclient, HttpSendModel httpSendModel,
            String getCharSet) throws Exception {

        HttpRequestBase httpRequest = buildHttpRequest(httpSendModel);

        if (httpSendModel.getUrl().startsWith("https://")) {
            simpleHttpclient.enableSSL();
        }

        try {
            HttpResponse response = simpleHttpclient.getHttpclient().execute(
                    httpRequest);
            int statusCode = response.getStatusLine().getStatusCode();

            if (isRequestSuccess(statusCode)) {
                return new SimpleHttpResponse(statusCode, EntityUtils.toString(
                        response.getEntity(), getCharSet), null);
            } else {
                return new SimpleHttpResponse(statusCode, null, response
                        .getStatusLine().getReasonPhrase());
            }

        } catch (Exception e) {
            throw new Exception("http请求异常", e);
        }

    }

    /**
     * @param httpSendModel
     * @return
     * @throws Exception
     */
    protected static HttpRequestBase buildHttpRequest(
            HttpSendModel httpSendModel) throws Exception {
        HttpRequestBase httpRequest;
        if (httpSendModel.getMethod() == null) {
            throw new Exception("请求方式未设定");
        } else if (httpSendModel.getMethod() == HttpMethod.POST) {

            String url = httpSendModel.getUrl();
            String sendCharSet = httpSendModel.getCharSet();
            List<HttpFormParameter> params = httpSendModel.getParams();

            List<NameValuePair> qparams = new ArrayList<NameValuePair>();
            if (params != null && params.size() != 0) {

                for (HttpFormParameter param : params) {
                    qparams.add(new BasicNameValuePair(param.getName(), param
                            .getValue()));
                }

            }

            HttpPost httppost = new HttpPost(url);
            try {
                httppost.setEntity(new UrlEncodedFormEntity(qparams,
                        sendCharSet));
            } catch (UnsupportedEncodingException e) {
                throw new Exception("构建post请求参数失败", e);
            }

            httpRequest = httppost;
        } else if (httpSendModel.getMethod() == HttpMethod.GET) {
            HttpGet httpget = new HttpGet(httpSendModel.buildGetRequestUrl());

            httpRequest = httpget;
        } else {
            throw new Exception("请求方式不支持：" + httpSendModel.getMethod());
        }

        return httpRequest;
    }

    /**
     * 请求是否成功
     *
     * @param statusCode
     * @return
     */
    public static boolean isRequestSuccess(int statusCode) {
        return statusCode == 200;
    }




}